// utils/uploadManager.js
const app = getApp()
/**
 * 文件上传管理器
 */

class UploadManager {
    /**
     * 文件上传
     * @param {Object} options 上传配置
     * @param {string} options.filePath 文件路径
     * @param {string} options.name 文件对应的key
     * @param {Object} options.formData 其他表单数据
     * @param {Function} options.success 成功回调
     * @param {Function} options.fail 失败回调
     */
    upload(options) {
      const fileExtension=this.getFileExtension(options.filePath);
      let url=app.globalData.baseURL;
      switch(fileExtension) {
        case 'mp3':
          url=url+'/api/file/upload/mp3';
          break;
        case 'mp4':
          url=url+'/api/file/upload/mp4';
          break;
        default:
          url=url+'/api/file/upload/img';
          break;
      }

      const {
        filePath,
        name = 'file',
        formData = {},
        success,
        fail
      } = options
  
      // 创建上传任务
      const uploadTask = wx.uploadFile({
        url,
        filePath,
        name,
        header: {
            'x-access-token': app.globalData.userToken,
            'x-access-employeeid': app.globalData.userEmployeeId,
            'x-access-companyid': app.globalData.userCompanyId
        },
        formData,
        success: (res) => {
          if (res.statusCode === 200) {
            let resObject=JSON.parse(res.data);
            let data = resObject.data;
            success && success(data)
          } else {
            fail && fail({
              errMsg: `上传失败，状态码: ${res.statusCode}`,
              statusCode: res.statusCode
            })
          }
        },
        fail: (err) => {
          fail && fail(err)
        }
      })
  
      return uploadTask
    }
  
    /**
     * 批量上传文件
     * @param {Array} files 文件列表
     * @param {Object} options 上传配置
     * @param {number} options.concurrency 并发数，默认3
     * @returns {Promise} Promise对象
     */
    async uploadAll(files, options = {}) {
      const { concurrency = 3 } = options
      const results = []
      const executing = []
      
      for (const file of files) {
        const p = this.upload(file).then(result => {
          results.push(result)
          executing.splice(executing.indexOf(p), 1)
        })
        executing.push(p)
        
        if (executing.length >= concurrency) {
          await Promise.race(executing)
        }
      }
      
      return Promise.allSettled(executing).then(() => results)
    }

    getFileExtension(filename) {
        // 处理通过 URL 传递的文件名，去除查询参数和哈希
        const name = filename.split(/[?#]/)[0];
        const parts = name.split('.');
        // 如果只有一个部分，说明没有扩展名
        if (parts.length === 1) {
          return '';
        }
        const extension = parts.pop().toLowerCase();
        // 如果最后一部分是空字符串（例如“file.”），则返回空字符串
        return extension === '' ? '' : extension;
      }
  }
  
  module.exports = new UploadManager()